<template>
	<view class="index">
		<view class="top">
			<view class="topbg">
				<image src="/static/img/index/162.png" mode="widthFix"></image>
			</view>
			<view class="top_1">
				<view class="left" @tap="areaChoose.show()">
					<view class="left_1 ellipsis_1">
						{{data.city}}
						<!-- <text class="left_1_text ellipsis_1"></text> -->
					</view>
					<text class="left_text">{{data.lives?.temperature}}°{{data.lives?.weather}}</text>
				</view>
				<view class="input" @tap="navTo('/pages/lifeSearch/index')">
					<image class="inputImg" src="/static/img/index/7.png" mode="widthFix"></image>
					<text class="input_value">请输入想查找的商品或服务</text>
				</view>
				<view class="right">
					<view class="right_1" @tap="chooseAddOrScan">
						<image class="right_1_img" src="/static/img/index/1.png" mode="widthFix"></image>
					</view>
					<view class="right_2" @tap="platformService">
						<image class="right_2_img" src="/static/img/index/2.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
			<view class="top_2">
				<view class="top_2_view" @tap="loginNavTo('/pages/makeMoney/index')">
					<image class="img" src="/static/img/index/3.png" mode="widthFix"></image>
					<text class="text">赚钱开店</text>
				</view>
				<view class="top_2_view" @tap="loginNavTo('/pages/qiangqiang/qiangqiang')">
					<image class="img" src="/static/img/index/4.png" mode="widthFix"></image>
					<text class="text">墙墙大厅</text>
				</view>
				<view class="top_2_view" @tap="loginNavTo('/pages/life/index')">
					<image class="img" src="/static/img/index/5.png" mode="widthFix"></image>
					<text class="text">生活购物</text>
				</view>
				<!-- @tap="loginNavTo('/pages/purse/purse')" -->
				<view class="top_2_view" @tap="jump">
					<image class="img" src="/static/img/index/170.png" mode="widthFix"></image>
					<text class="text">企业服务</text>
				</view>
			</view>
		</view>
		<scroll-view class="scrollView" scroll-y="true">
			<view @tap="headToNav" class="contentTop">
				<view class="left">
					<image v-if="headLine?.type==2" class="left_img" src="/static/img/index/13.png" mode="widthFix">
					</image>
					<image style="width: 100%;height: 50rpx;" v-if="headLine?.type==1" class="left_img"
						:src="data.httpUrl+'/app/file/viewFile?fileId='+headLine?.avatarId" mode="aspectFill"></image>
					<text class="left_text">{{headLine.type == 2? headLine.time:headLine.date}}</text>
				</view>
				<view class="right">
					<text class="right_text_box">
						<text class="right_text"
							style="font-size: 32rpx;">{{headLine?.content?headLine?.content:'暂无头条'}}</text>
					</text>
				</view>
			</view>
			<view class="contentCenter">
				<!-- <image class="contentCenter_img" src="/static/img/index/14.png" mode="widthFix"></image> -->
				<view class="contentCenter_view">
					<!-- <view class="contentCenter_top_view">
						<image class="contentCenter_top_img" src="/static/img/index/21.png" mode="widthFix"></image>
						<text class="advancedServices">更多高级服务，轻松助您提升收入</text>
					</view> -->

					<view class="contentCenterList">
						<view class="contentCenterList_Item"
							@tap="checkMembership('/pages/homeServer/housekeeper/index')">
							<image class="contentCenterList_Item_img" src="/static/img/homeServer/gjvip.png"
								mode="widthFix">
							</image>
							<text class="contentCenterList_Item_text">管家</text>
						</view>
						<view class="contentCenterList_Item"
							@tap="checkMembership('/pages/homeServer/humanResources/index')">
							<image class="contentCenterList_Item_img" src="/static/img/homeServer/hrvip.png"
								mode="widthFix">
							</image>
							<text class="contentCenterList_Item_text">HR</text>
						</view>
						<view class="contentCenterList_Item" @tap="checkMembership('/pages/homeServer/finance/index')">
							<image class="contentCenterList_Item_img" src="/static/img/homeServer/cwvip.png"
								mode="widthFix">
							</image>
							<text class="contentCenterList_Item_text">财务</text>
						</view>
						<view class="contentCenterList_Item" @tap="loginNavTo('/pages/homeServer/team/index')">
							<image class="contentCenterList_Item_img" src="/static/img/index/18.png" mode="widthFix">
							</image>
							<text class="contentCenterList_Item_text">团队</text>
						</view>
					</view>
				</view>
			</view>
			<view class="news">
				<text class="newsText">最新消息</text>
				<text @tap="toMsg" class="newsText" style="float: right;">更多</text>
				<view @tap="toMsgMores(item)" class="newsItem" v-for="(item,index) in data.logisticsList" :key="index">
					<image class="left" src="/static/img/index/19.png" mode="widthFix"></image>
					<view class="right">
						<text class="rightTopText">{{item.stateName}}</text>
						<view class="rightTopBot">
							<text class="rightTopBotText1">{{item.msgContent}}</text>
							<text class="rightTopBotText2">{{item.msgTime}}</text>
						</view>
						<view v-if="item.state=='N'" class="msg_content_right_count"></view>
					</view>
				</view>
			</view>
			<view class="recruit">
				<!-- <image @click="jump" src="/static/img/index/150.png" mode="widthFix"></image> -->
				<!-- <view class="recruitItem">
					<view class="top" @tap="loginNavTo('/pages/jobHunting/jobHunting')">
						<image class="left" src="/static/img/index/168.png" mode="widthFix"></image>
						<image class="right" src="/static/img/index/20.png" mode="widthFix"></image>
					</view>
					<view class="imgs">
						<view @tap="loginNavTo('/pages/jobHunting/jobDetail?data='+JSON.stringify(item))" class="imgs1 imgs2"
							v-for="(item,index) in data.hireList.slice(0,6)" :key="index">
							<image :src="data.httpUrl+'/app/file/viewFile?fileId='+item.avatar" mode="aspectFill">
							</image>
							{{item.positionName}}
						</view>
					</view>
				</view> -->
				<view class="recruitItem">
					<view class="top" @tap="loginNavTo('/pages/life/index')">
						<text class="left">推荐</text>
						<image class="right" src="/static/img/index/20.png" mode="widthFix"></image>
					</view>
					<view class="imgs">
						<view @tap="loginNavTo('/pages/lifestyleProducts/index?id='+item.id+'&productType=PRODUCT')"
							class="imgs1 imgs2" v-for="(item,index) in data.goodsList.slice(0,8)" :key="index">
							<image :src="data.httpUrl+'/app/file/viewFile?fileId='+item.fileId" mode="aspectFill">
							</image>
							<view class="" style="display: flex;flex-wrap: wrap;align-items: flex-end;"   v-if="item.preferentialPrice && item.preferentialPrice != 0">
								<text style="color:#FF5233;font-size:24rpx;margin-right: 10rpx;">{{item.preferentialPrice}}</text>
								<text style="text-decoration:line-through;color: #BFBFBF;font-size: 20rpx;">¥{{item.price}}</text>
							</view>
							<view v-else style="color:#FF5233;">￥{{item.price}}</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<areaSelect ref='areaChoose' @confirm='areaConfirm'></areaSelect>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive,getCurrentInstance } from 'vue'
	import { productPageProduct, listLastLogisticsMsg,supportProduct } from '@/utils/api/homepage'
	import { onShow } from '@dcloudio/uni-app'
	import areaSelect from '@/components/area-choose/area-choose.vue'
	import { currentHeadline, getServiceImId, queryHomePageInfo,addFriend } from '@/utils/api/index.ts'
	import { openVipFlag, loginCheck } from '@/utils/api/userInfo.ts'
	import { useCounterStore } from '@/stores/counter';
	import { lastThreeMsg } from '@/utils/api/msg.ts'
	import { verifyOrder } from '@/utils/api/shop'
	import {
		setDialogView
	} from '@/utils/dialogView.ts'
	const areaChoose = ref();
	const data = reactive<any>({
		goodsList: [],
		hireList: [],
		httpUrl: getApp().globalData.baseUrl,
		logisticsList: [],
		city: uni.getStorageSync('city'),
		lives: { weather: "", temperature: '' },
		stm: null
	})
	const getLives = () => {
		uni.request({
			method: 'GET',
			url: 'https://restapi.amap.com/v3/weather/weatherInfo',
			data: {
				key: '1ec431a97d8606882d248314988e38cb',
				city: data.city
			},
			success: (e : any) => {
				data.lives = e.data.lives.length ? e.data.lives[0] : {};
			}
		})
	}
	// 添加好友
	
	const chooseAddOrScan=()=>{
		
		uni.showActionSheet({
			itemList: ['搜索好友','扫一扫'],
			success:function(e){
				if (e.tapIndex == 0) {
					toAdd()
				}else if(e.tapIndex==1){
					uni.scanCode({
						success: function (res) {
							console.log(res,'resss')
							const codeData=res.result
							console.log('二维码数据',codeData)
							const jsonData=JSON.parse(codeData)
							const dataType=jsonData?.dataType
							const dataCode=jsonData?.dataCode;
							if(dataType=='addFriend'){
								addFriend({data:{friendUserId:dataCode}}).then(res=>{
									uni.showToast({
										title: '添加好友成功',
										icon: 'success'
									});
								})
							}else if(dataType=='productDetail'){
								const url='/pages/lifestyleProducts/index?id='+dataCode
								navTo(url)
							}else if(dataType=='verifyProduct'){
								verifyOrder({ data: { verifyCode: dataCode } }).then((res) => {
									if (res.code == 200) {
										uni.showToast({
											title: '核销成功！',
											icon: 'none'
										})
									}
								})
							}
						}
					})
				}
			}
		})
		
	}
	
	const toAdd = () => {
		loginNavTo('/pages/index/search')
	}
	if (!data.city) {
		const token=uni.getStorageSync('token')
		if(token){
			setDialogView('ACCESS_FINE_LOCATION').then((res)=>{
				if(res == 1){
					uni.getLocation({
						type: 'gcj02',
						geocode: true,
						success: function (res) {
							data.city = res.address.district;
							getLives()
						},
						fail:()=>{
							uni.setStorageSync('city','红塔区');
							data.city = '红塔区'
							getLives()
						}
					})
				}else{
					uni.setStorageSync('city','红塔区');
					data.city = '红塔区'
					getLives()
				}
			})
			
		}else{
			uni.setStorageSync('city','红塔区');
			data.city = '红塔区'
			getLives()
		}	
	} else {
		getLives()
	}
	// queryHomePageInfo().then((res) => {
	// 	data.hireList = res.data.list;
	// })
	const areaConfirm = e => {
		uni.setStorageSync('city', e.addressList[e.addressList.length - 1])
		data.city = e.addressList[e.addressList.length - 1]
		getLives()
	}
	// 去系统消息
	const toMsg = () => {
		loginNavTo('/pages/index/msg')
	}
	const toMsgMores = (item : any) => {
		loginNavTo(`/pages/index/msgMore?msgId=${item.id}`)
		item.state = 'Y'
	}



	const navTo = (url : String) : void => {
		console.log('执行')
		uni.navigateTo({ url })
	}
	const loginNavTo = (url : String) : void => {
		loginCheck().then(res => {
			uni.navigateTo({ url })
		})
	}

	const statusBarHeight = getApp().globalData.statusBarHeight;
	// productPageProduct().then((res) => {
	// 	data.goodsList = res.data.list;
	// })
	const secondsToTime = (totalSeconds) => {
		// 计算小时数
		const hours = Math.floor(totalSeconds / 3600);

		// 计算剩余的分钟数（不包括小时部分）
		const minutes = Math.floor((totalSeconds % 3600) / 60);

		// 计算剩余的秒数（不包括小时和分钟部分）
		const secs = totalSeconds % 3600 % 60;

		// 将小时、分钟和秒转换为两位数字格式，如果不足则前面补0
		const hoursStr = String(hours).padStart(2, '0');
		const minutesStr = String(minutes).padStart(2, '0');
		const secondsStr = String(secs).padStart(2, '0');

		// 组合成所需的格式 hh:mm:ss
		const formattedTime = `${hoursStr}:${minutesStr}:${secondsStr}`;

		return formattedTime;
	}
	const headLine = ref<any>({})
	const getList = async () => {
		const head = await currentHeadline()
		headLine.value = head.data;
		headlineCalculation()

	}

	const loadThreeMsg = () => {
		lastThreeMsg().then((res) => {
			data.logisticsList = res.data
		})
	}


	const checkMembership = async (url : string) => {
		// uni.navigateTo({
		// 	url
		// })
		// return;
		const { success, data } = await openVipFlag()
		if (data) {
			uni.navigateTo({
				url
			})
			return
		}

		// navTo('/pages/homeServer/finance/index')
		uni.showModal({
			title: '提示',
			content: "您未开通尊享服务，跳转去开通？",
			success(res) {
				console.log(res)
				res.confirm && uni.navigateTo({
					url: "/pages/homeServer/openMembership/index"
				})
			}
		})

	}
	const headlineCalculation = ()=>{
		if (data.stm) {
			clearInterval(data.stm)
		}
		if (headLine.value.type == 1) {
			headLine.value.date = secondsToTime(headLine.value.validTime)
			data.stm = setInterval(() => {
				headLine.value.validTime -= 1;
				headLine.value.date = secondsToTime(headLine.value.validTime)
				if(headLine.value.validTime == 0){
					getList()
				}
			}, 1000)
		}
	}

	const headToNav = () => {
		if (headLine.value.type == 1) {
			if (!headLine.value.trendsId) {
				return
			}
			uni.navigateTo({
				url: `/pages/qiangqiang/qiangMore?id=${headLine.value.trendsId}&areaType=NATIONAL`
			})
		} else {

			uni.navigateTo({
				url: `/pages/news/index?newsId=${headLine.value.id}`
			})

		}


	}
	const counterStore = useCounterStore();
	onShow(() => {
		counterStore.resetCountdowns()
		getList()
		uni.$off('updateHeadLine')
		uni.$on('updateHeadLine', function () {
			currentHeadline().then(res => {
				headLine.value = res.data;
				headlineCalculation()
			})
		})

		uni.$off('refreshMsg')
		uni.$on('refreshMsg', function (msgData) {
			data.logisticsList.unshift(msgData)
		})

		loadThreeMsg()
		supportProduct().then((res) => {
			res.data.map((item)=>{
				item.preferentialPrice = item.preferentialPrice + '';
				item.price = item.price + '';
				if (item.price.indexOf('.') == -1) {
					item.price = item.price + '.00'
				}
				if(item.preferentialPrice*1 && item.preferentialPrice.indexOf('.') == -1){
					item.preferentialPrice = item.preferentialPrice + '.00'
				}
			})
			data.goodsList = res.data;
		})
		queryHomePageInfo().then((res) => {
			data.hireList = res.data.list;
		})
		
		data.city=uni.getStorageSync('city')
	})
	// 前往招聘
	const jump = _ => {
		loginCheck().then(res => {
			uni.navigateTo({
				url: '/pages/choice/choice'
			})
		})
	}

	const platformService = () => {
		// data.info.serviceUserId = '1848031351512059906'
		uni.navigateTo({
			url: '/pages/my/helpGroupCenter'
		})
		// loginCheck().then(r => {
		// 	getServiceImId().then(res => {
		// 		const conversationID = `C2C${res.data}`;
		// 		uni.navigateTo({ url: `/pages/TUIKit/components/TUIChat/index?conversationID=${conversationID}&userId=${res.data}` });
		// 	})
		// })
	}
</script>

<style lang="scss" scoped>
	.scrollView {
		position: relative;
		z-index: 2;
		flex: 1 auto;
		padding: 24rpx 24rpx;
		height: 0;
		box-sizing: border-box;
		overflow: auto;
		border-radius: 24rpx 24rpx 0 0;
		margin-top: -40rpx;
		background: linear-gradient(to bottom, #F5F6FA, #F7F6F9);
	}

	.contentCenter_top_view {
		display: flex;
		flex-direction: column;
	}

	.advancedServices {
		color: #fff;
		margin-top: 20rpx;
	}

	.recruit {
		display: flex;
		margin-top: 24rpx;
		flex-wrap: wrap;
		flex-direction: row;
		justify-content: space-between;

		>image {
			width: 340rpx;
		}

		.recruitItem {
			width: 100%;
			padding: 20rpx;
			background: #fff;
			border-radius: 21rpx;

			.top {
				display: flex;
				align-items: center;
				flex-direction: row;
				justify-content: space-between;
				height: 80rpx;
				padding-bottom: 20rpx;

				.left {
					width: 72rpx;
				}

				.right {
					width: 36rpx;
				}
			}

			.imgs {
				display: flex;
				flex-wrap: wrap;
				flex-direction: row;
				justify-content: space-between;

				.imgs1 {
					display: flex;
					flex-direction: column;
					background: #ccc;
					font-size: 24rpx;
					margin-bottom: 10rpx;
					width: 200rpx;
					height: 200rpx;
					image {
						border-radius: 16rpx;
						width: 200rpx;
						height: 200rpx;
						margin-bottom: 10rpx;
					}
				}

				.imgs2 {
					background: transparent;
				}
			}
		}
	}

	.contentCenter {


		position: relative;
		margin: 24rpx 0;

		.contentCenter_img {
			width: 100%;
		}

		.contentCenter_view {
			width: 100%;
			height: 100%;

			.contentCenterList {
				display: flex;
				margin-top: 23rpx;
				padding: 16rpx;
				flex-direction: row;
				justify-content: space-between;
				border-radius: 24rpx;
				background: linear-gradient(to right, #DFDAFF, #EDFFFE);
			}

			.contentCenterList_Item {
				display: flex;
				align-items: center;
				flex-direction: column;
			}

			.contentCenterList_Item_img {
				width: 96rpx;
			}

			.contentCenterList_Item_text {
				font-size: 24rpx;
				color: #262626;
				margin-top: 10rpx;
			}
		}

		.contentCenter_top_img {
			width: 206rpx;
		}
	}

	.news {
		padding: 24rpx;
		background: #fff;
		border-radius: 24rpx;

		.newsText {
			font-size: 32rpx;
			color: #000;
		}

		.newsItem {
			display: flex;
			flex-direction: row;
			align-items: center;
			align-content: center;
			margin-top: 20rpx;

			.left {
				width: 48rpx;
				margin-right: 21rpx;
			}

			.right {
				flex: 1;
				width: 0;

				.rightTopText {
					font-size: 28rpx;
					color: #262626;
				}

				.rightTopBot {
					margin-top: 8rpx;
					display: flex;
					flex-direction: row;

					.rightTopBotText1 {
						flex: 1;
						font-size: 24rpx;
						color: #595959;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						margin-right: 20rpx;
					}

					.rightTopBotText2 {
						font-size: 24rpx;
						color: #595959;
					}
				}
			}
		}
	}

	.index {
		display: flex;
		flex-direction: column;
		overflow: auto;
		height: 100vh;
		// background: linear-gradient(#723AE4, #756BFE, #5F48FF);

		>.top {
			padding-top: var(--status-bar-height);
			padding-bottom: 50rpx;
			position: relative;

			.topbg {
				position: absolute;
				left: 0;
				top: 0;
				right: 0;
				bottom: -20rpx;
				background: url('/static/img/index/161.png') no-repeat;
				background-size: 100% 100%;
				display: flex;
				align-items: flex-end;
				justify-content: center;
				padding-bottom: 120rpx;

				image {
					width: 236rpx;

				}
			}

			.top_1 {
				position: relative;
				z-index: 1;
				padding: 0 24rpx;
				display: flex;
				padding-top: 44rpx;
				flex-direction: row;

				.left {
					max-width: 100rpx;

					.left_1 {
						font-size: 24rpx;
						color: #fff;
					}

					.left_text {
						font-size: 20rpx;
						color: #fff;
						margin-top: 10rpx;
					}
				}

				.input {
					height: 64rpx;
					background: rgba(255, 255, 255, 0.90);
					border-radius: 60rpx;
					flex: 1;
					margin: 0 24rpx;
					display: flex;
					padding: 0 27rpx;
					flex-direction: row;
					align-items: center;

					.inputImg {
						width: 22.5rpx;
					}

					.input_value {
						flex: 1;
						margin-left: 7rpx;
						color: #8f8f8f;
					}
				}

				.right {
					display: flex;
					flex-direction: row;

					.right_1,
					.right_2 {
						width: 64rpx;
						height: 64rpx;
						border-radius: 64rpx;
						display: flex;
						align-items: center;
						flex-direction: column;
						justify-content: center;
						background: rgba(255, 255, 255, 0.20);
					}

					.right_2 {
						margin-left: 12rpx;
					}

					.right_1_img,
					.right_2_img {
						width: 36rpx;
					}
				}
			}

			.top_2 {
				position: relative;
				z-index: 1;
				padding: 0 48rpx;
				display: flex;
				flex-direction: row;
				margin-top: 52rpx;
				justify-content: space-between;

				.img {
					width: 96rpx;
					margin-bottom: 10rpx;
				}

				.top_2_view {
					display: flex;
					align-items: center;
					flex-direction: column;
				}

				.text {
					font-size: 24rpx;
					color: #FFFFFF;
				}
			}
		}

		.contentTop {
			display: flex;
			flex-direction: row;
			align-items: center;
			padding: 12rpx 16rpx;
			border-radius: 24rpx;
			background: #fff;

			.left {
				position: relative;
				width: 120rpx;
				height: 84rpx;
				.left_img {
					width: 120rpx;
				}

				.left_text {
					font-size: 24rpx;
					color: #000;
					position: absolute;
					bottom: 0;
					left: 0;
					width: 100%;
					text-align: center;
				}
			}

			.right {
				margin-left: 16rpx;
				flex: 1;
				width: 0;

				.right_text {
					font-size: 24rpx;
				}

				.right_text_1 {
					color: #6B64D3;
					font-size: 24rpx;
				}
			}
		}
	}

	.msg_content_right_count {
		// margin-top: 33rpx;
		margin-left: 568rpx;
		width: 20rpx;
		height: 20rpx;
		background: #FF263F;
		border-radius: 20rpx;
		border: 2rpx solid #FFFFFF;
		display: flex;
		align-items: right;
		justify-content: right;
		font-size: 20rpx;
		color: #fff;
	}
</style>